package com.cbnu.SmartCampusLife;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Display;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.BaseAdapter;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.aphidmobile.flip.FlipViewController;

@SuppressLint({ "WorldReadableFiles", "SetJavaScriptEnabled", "HandlerLeak" })
public class MainMenu extends Activity {
    /** Called when the activity is first created. */
	
	private boolean loginChk; //true is login
	private int term = 1; //Calculating term
	
	String lectureName[][] = new String[15][9];
	String lectureProf[][] = new String[15][9];
	String lectureLoc[][] = new String[15][9];
	String lectureNum[][] = new String[15][9];
	String lecSum[][] = new String[3][12];
	int length = 0; //Save length of lecSum
	int column = 15;
	int row = 9;
	int x = 0;
	int lecColor[] = {Color.rgb(216, 216, 216), Color.rgb(231, 225, 203), Color.rgb(134, 175, 220)
						, Color.rgb(232, 184, 184), Color.rgb(165, 231, 187), Color.rgb(194, 223, 165)
						, Color.rgb(163, 215, 221), Color.rgb(233, 187, 219), Color.rgb(231, 231, 138)};
	
	private FlipViewController flipView;
	private static String path = "/data/data/com.cbnu.SmartCampusLife/files/";
	private int width;
	private int height;
	private Bitmap bmp;

	private class LectureParse extends Thread {
		@Override
		public void run() {
			lectureName[0][0] = "교시";
			lectureName[0][1] = "월";
			lectureName[0][2] = "화";
			lectureName[0][3] = "수";
			lectureName[0][4] = "수A";
			lectureName[0][5] = "목";
			lectureName[0][6] = "금";
			lectureName[0][7] = "금A";
			lectureName[0][8] = "토";
			
			for(int a = 1; a < 15; a++) lectureName[a][0] = String.valueOf(a - 1);
			
			try {
				
				FileInputStream fis = openFileInput("timeMy.txt");
				BufferedInputStream bis = new BufferedInputStream(fis);
				BufferedReader br = new BufferedReader(new InputStreamReader(bis));
				int i = 1, j = 1; // Row and column variable
				String str = null;
				while((str = br.readLine()) != null) {
					if(str.matches(".*" + "<td width=\"90\" height=\"" + ".*" + "\" align=\"center\">" + ".*") || str.matches(".*" + "<td width=\"90\" rowspan=\"" + ".*" + "\" align=\"center\"><span style=\"font-size:8pt\">" + ".*")) {
						str = str.replaceAll("\t\t\t\t\t\t" + "<td width=\"90\" height=\"" + ".*" + "\" align=\"center\"><span style=\"font-size:8pt\">", "");
						str = str.replaceAll("\t\t\t\t\t\t" + "<td width=\"90\" rowspan=\"" + ".*" + "\" align=\"center\"><span style=\"font-size:8pt\">", "");
						
						// Wed A & Fri A Lecture
						if(i == 3 || i == 6 || i == 9) { // Period 2, 5, 8 have 'A' lecture. So, need to sort
							if(j == 4 || j == 7) j++;
							else if(j == 9) j = 4;
							else if(j == 5) j = 7;
							else if(j == 8) j = 9;
							
						}
						if(i == 4 || i == 7  || i == 10 || i >= 12) { // Period 3, 6, 9, 11~ have no 'A' lecture. So, pass 'A' lecture
							if(j == 4 || j == 7) j++;
						}
						
						//Next Period
						if(j == 9) {
							j = 1;
							i++;
						}
						
						if(str.matches(".*&nbsp;.*") || str.equals("<br></span></td>")) {
							j++;
						}
						else  {
							String temp = null;
							int t = 0;
							//lectureName
							t = str.indexOf("<br><a");
							temp = str.substring(0, t);
							temp = temp.replaceAll("<br>", "");
							lectureName[i][j] = temp;
							
							//lectureNum
							t = str.indexOf("');\">");
							str = str.substring(t + 5, str.length());
							t = str.indexOf("</a>");
							temp = str.substring(0, t);
							lectureNum[i][j] = temp;
							
							//lectureProf
							t = str.indexOf("<br>");
							str = str.substring(t + 4, str.length());
							t = str.indexOf("<br>");
							temp = str.substring(0, t);
							lectureProf[i][j] = temp;
							
							//lectureLoc
							str = str.substring(t + 4, str.length());
							t = str.indexOf("</span>");
							temp = str.substring(0, t);
							lectureLoc[i][j] = temp;
							
							//Check lecSum
							for(int l = 0; l < length + 1; l++) {
								if(lecSum[0][l] == null) {
									lecSum[0][l] = lectureName[i][j];
									lecSum[1][l] = lectureLoc[i][j];
									lecSum[2][l] = (i + 7) + ":00 (" + lectureName[0][j];
									length++;
									break;
								}
								else if(lecSum[0][l] != null && lecSum[0][l].equals(lectureName[i][j])) {
									if(!lecSum[2][l].matches(".*" + lectureName[0][j] + ".*")) {
										if(!lecSum[2][l].matches(".*" + (i + 7) + ":00"  + ".*")) {
											lecSum[2][l] += "), " + (i + 7) + ":00 (" + lectureName[0][j];
										}
										else lecSum[2][l] += " " + lectureName[0][j];
									}
									break;
								}
							}
							
							j++;
						}
					}
				}
				
				br.close();
				bis.close();
				fis.close();
				
			} catch(Exception e) {;}
			
			//Timetable optimization
			optimizeTimeTable();
		}
	}
	
	private void optimizeTimeTable() {
		//Find empty row
		for(int b = 1; b < row; b++) {
			for(int a = 1; a < column; a++) {
				if(lectureName[a][b] != null) {
					x = 1;
					Log.d("lecture Exsist", lectureName[a][b]);
					break;
				}
			}
			
			if(x == 0) {
				row--;
				Log.d("Optimizing", "Delete Row : " + b + ", row=" + row);
				for(int a = 0; a < column; a++)
					for(int z = b; z < row; z++) {
						lectureName[a][z] = lectureName[a][z+1];
						lectureNum[a][z]  = lectureNum[a][z+1];
						lectureProf[a][z] = lectureProf[a][z+1];
						lectureLoc[a][z]  = lectureLoc[a][z+1];
					}
				b--;
			}
			
			x = 0;
		}
		
		//Find empty column
		x = 0;
		for(int a = 1; a < column; a++) {
			for(int b = 1; b < row; b++) {
				if(lectureName[a][b] != null) {
					x = 1;
					Log.d("lecture Exsist", lectureName[a][b]);
					break;
				}
			}
			
			if(x == 0) {
				column--;
				Log.d("Optimizing", "Delete Column : " + a + ", column=" + column);
				for(int b = 0; b < row; b++)
					for(int z = a; z < column; z++) {
						lectureName[z][b] = lectureName[z+1][b];
						lectureNum[z][b] = lectureNum[z+1][b];
						lectureProf[z][b] = lectureProf[z+1][b];
						lectureLoc[z][b] = lectureLoc[z+1][b];
					}
				a--;
			}
			
			x = 0;
		}
	}
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        Display display = ((WindowManager)getSystemService(WINDOW_SERVICE)).getDefaultDisplay();
        width = display.getWidth();
        height = display.getHeight();
        Log.d("UserLog : Activity Size", "width : " +  width + ", height : " + height);
        
        loginChk = getIntent().getBooleanExtra("loginChk", false);
        Log.d("loginChk", loginChk + " ");
        Calendar now = Calendar.getInstance();
		int year = now.get(Calendar.YEAR);
		int month = now.get(Calendar.MONTH) + 1;
		int day = now.get(Calendar.DAY_OF_MONTH);
		Log.d("Today", year + "/" + month + "/" + day);
		if ((month == 6 && day > 18) || month == 7) term = 2;
		else if(7 < month || (month <= 12 && day < 16)) term = 3;
		else if((month == 12 && day > 15) || month == 1) term = 4;
		else term = 1;
        if(loginChk == true){
	        class MyJavaScriptInterface{
	    		@SuppressWarnings("unused")
				public void showHTML(String html){
	    			FileOutputStream fos;
	    			try {
	    				fos = openFileOutput("timeMy.txt", Context.MODE_WORLD_READABLE);
	    				fos.write(html.getBytes("UTF-8"));
	    				fos.close();
	    				Log.d("timeMy", "Writing Success!");
	    			} catch (Exception e) {
	    				e.printStackTrace();
	    			}
    				Thread lp = new LectureParse();
    		        lp.start();
	    		}
	    	}
	    	
	        LayoutInflater inflater = LayoutInflater.from(this);
	        View layout = inflater.inflate(R.layout.activity_main_menu, null);
	    	WebView webview = (WebView)layout.findViewById(R.id.mainmenu_webView);
	    	webview.getSettings().setJavaScriptEnabled(true);
	    	webview.getSettings().setBuiltInZoomControls(true);
	    	webview.addJavascriptInterface(new MyJavaScriptInterface(), "HTMLOUT");
	        webview.setWebViewClient(new WebViewClient(){   //현재의 엑티비티 내에서 url을 보여주고자 할 경우 설정.
	            @Override
	    		public void onPageFinished(WebView view, String url) {
	    			super.onPageFinished(view, url);
	    			try {
	    				view.loadUrl("javascript:window.HTMLOUT.showHTML('<body>'+document.getElementsByTagName('body')[0].innerHTML+'</body>');");
	    			} catch (Exception e) {
	    				e.printStackTrace();
	    			}
	            }
	        });
	        
			Log.d("Timetable URL", "http://gaesin.chungbuk.ac.kr/jsp/lesn/timeMy.jsp?SHTM=" + term + "&YY="+ year);
	        webview.loadUrl("http://gaesin.chungbuk.ac.kr/jsp/lesn/timeMy.jsp?SHTM=" + term + "&YY=" + year);
        }
        else {
        	Thread lp = new LectureParse();
        	lp.start();
        }
        
        
        setTitle(R.string.title_activity_main_menu);
        flipView = new FlipViewController(this);
        flipView.setAdapter(new MyBaseAdapter(this));
        setContentView(flipView);
    }
    
	@Override
	protected void onResume() {
		super.onResume();
		flipView.onResume();
	}

	@Override
	protected void onPause() {
		super.onPause();
		flipView.onPause();
	}
    
    private class MyBaseAdapter extends BaseAdapter {
		private  List<Data> IMG_DESCRIPTIONS = new ArrayList<Data>();

		{
			IMG_DESCRIPTIONS.add(new Data("개인수업시간표", BitmapFactory.decodeResource(getResources(), R.drawable.empty_timetable), new Intent(MainMenu.this, TimeTable.class),
					"충북대 지도", BitmapFactory.decodeResource(getResources(), R.drawable.map), new Intent(MainMenu.this, Map.class),
					"충북대 SNS", BitmapFactory.decodeResource(getResources(), R.drawable.sns), new Intent(MainMenu.this, SNS.class)));
			IMG_DESCRIPTIONS.add(new Data("전자학생증", BitmapFactory.decodeResource(getResources(), R.drawable.empty_estudent), new Intent(MainMenu.this, Estudent.class),
					"종합정보시스템+", BitmapFactory.decodeResource(getResources(), R.drawable.tis), new Intent(MainMenu.this, TISMenu.class),
					"도움말", BitmapFactory.decodeResource(getResources(), R.drawable.help), new Intent(MainMenu.this, Help.class)));
		}

		private LayoutInflater inflater;

		private MyBaseAdapter(Context context) {
			inflater = LayoutInflater.from(context);
		}

		public int getCount() {
			return IMG_DESCRIPTIONS.size();
		}

		public Object getItem(int position) {
			return position;
		}

		public long getItemId(int position) {
			return position;
		}

		public View getView(int position, View convertView, ViewGroup parent) {
			View layout = convertView;
			if (convertView == null)
				layout = inflater.inflate(R.layout.activity_main_menu, null);

			final Data data = IMG_DESCRIPTIONS.get(position);
			
			TextView titleView = (TextView) layout.findViewById(R.id.title1);
			titleView.setText(data.title1);
			ImageButton photoView = (ImageButton) layout.findViewById(R.id.photo1);
			bmp = data.imageFilename1;
			if(data.title1.equals("개인수업시간표")) {
				File chk = new File(path + "timeTable.jpg");
		        if(chk.isFile()) bmp = BitmapFactory.decodeFile(path + "timeTable.jpg");
		        if(bmp == null) bmp = data.imageFilename1;
		        
		        ImageView pageArrow1 = (ImageView)layout.findViewById(R.id.pageArrow1);
		        pageArrow1.setVisibility(ImageView.VISIBLE);
		        ImageView pageArrow2 = (ImageView)layout.findViewById(R.id.pageArrow2);
		        pageArrow2.setVisibility(ImageView.INVISIBLE);
			}
			else if(data.title1.equals("전자학생증")) {
				File chk = new File(path + "eStudent.jpg");
		        if(chk.isFile()) bmp = BitmapFactory.decodeFile(path + "eStudent.jpg");
		        if(bmp == null) bmp = data.imageFilename1;
		        
		        ImageView pageArrow1 = (ImageView)layout.findViewById(R.id.pageArrow1);
		        pageArrow1.setVisibility(ImageView.INVISIBLE);
		        ImageView pageArrow2 = (ImageView)layout.findViewById(R.id.pageArrow2);
		        pageArrow2.setVisibility(ImageView.VISIBLE);
			}
			if(bmp != null && bmp.getWidth() / 2 - width / 4 > 0 && bmp.getHeight() / 2 - (height / 6) > 0) {
				bmp = Bitmap.createBitmap(bmp, bmp.getWidth() / 2 - width / 2, bmp.getHeight() / 2 - (height / 3), width - 14, (height / 3) * 2 - 14);
				Log.d("UserLog : FlipView 1st", "width : " +  bmp.getWidth() + ", height : " + bmp.getHeight());
			}
			photoView.setImageBitmap(bmp);
			photoView.setOnClickListener(new View.OnClickListener() {
				public void onClick(View v) {
		        	data.intent1.putExtra("term", term);
		        	for(int i = 0; i < column; i++) {
		        		data.intent1.putExtra("lectureName["+ i + "]", lectureName[i]);
		        		data.intent1.putExtra("lectureProf["+ i + "]", lectureProf[i]);
		        		data.intent1.putExtra("lectureLoc["+ i + "]", lectureLoc[i]);
		        		data.intent1.putExtra("lectureNum["+ i + "]", lectureNum[i]);
		        	}
		        	data.intent1.putExtra("column", column);
		        	data.intent1.putExtra("row", row);
		        	data.intent1.putExtra("lecSum[0]", lecSum[0]);
		        	data.intent1.putExtra("lecSum[1]", lecSum[1]);
		        	data.intent1.putExtra("lecSum[2]", lecSum[2]);
		        	startActivity(data.intent1);
				}
			});
			
			titleView = (TextView) layout.findViewById(R.id.title2);
			titleView.setText(data.title2);
			bmp = data.imageFilename2;
			if(bmp.getWidth() / 2 - width / 4 > 0 && bmp.getHeight() / 2 - (height / 6) > 0) {
				bmp = Bitmap.createBitmap(bmp, bmp.getWidth() / 2 - width / 4, bmp.getHeight() / 2 - (height / 6), width / 2 - 14, height / 3 - 14);
				Log.d("UserLog : FlipView 2st", "width : " +  bmp.getWidth() + ", height : " + bmp.getHeight());
			}
			photoView = (ImageButton) layout.findViewById(R.id.photo2);
			photoView.setImageBitmap(bmp);			
			photoView.setOnClickListener(new View.OnClickListener() {
				public void onClick(View v) {
		        	for(int i = 0; i < column; i++) {
		        		data.intent2.putExtra("lectureName["+ i + "]", lectureName[i]);
		        		data.intent2.putExtra("lectureProf["+ i + "]", lectureProf[i]);
		        		data.intent2.putExtra("lectureLoc["+ i + "]", lectureLoc[i]);
		            	data.intent2.putExtra("lectureNum["+ i + "]", lectureNum[i]);
		        	}
		        	data.intent2.putExtra("column", column);
		        	data.intent2.putExtra("row", row);
		        	data.intent2.putExtra("lecSum[0]", lecSum[0]);
		        	data.intent2.putExtra("lecSum[1]", lecSum[1]);
		        	data.intent2.putExtra("lecSum[2]", lecSum[2]);
		        	int stuIdChk = 0;
		        	try {
		    			FileInputStream fis = openFileInput("stu_id.txt");
		    			BufferedInputStream bis = new BufferedInputStream(fis);
		    			BufferedReader br = new BufferedReader(new InputStreamReader(bis));
		    			//If student are admitted before 2009-year, then use old building name, else use new building name
		    			stuIdChk = Integer.parseInt(br.readLine()) < 2009000000 ? 1 : 0; 
		    			
		    		} catch(Exception e) { e.printStackTrace(); }
		        	data.intent2.putExtra("stuIdChk", stuIdChk);
		        	startActivity(data.intent2);
				}
			});
			
			titleView = (TextView) layout.findViewById(R.id.title3);
			titleView.setText(data.title3);
			bmp = data.imageFilename3;
			if(bmp.getWidth() / 2 - width / 4 > 0 && bmp.getHeight() / 2 - (height / 6) > 0) {
				bmp = Bitmap.createBitmap(bmp, bmp.getWidth() / 2 - width / 4, bmp.getHeight() / 2 - (height / 6), width / 2 - 14, height / 3 - 14);
			}
			photoView = (ImageButton) layout.findViewById(R.id.photo3);
			photoView.setImageBitmap(bmp);
			photoView.setOnClickListener(new View.OnClickListener() {
				public void onClick(View v) {
		        	for(int i = 0; i < column; i++) {
		        		data.intent3.putExtra("lectureName["+ i + "]", lectureName[i]);
		        		data.intent3.putExtra("lectureProf["+ i + "]", lectureProf[i]);
		        		data.intent3.putExtra("lectureLoc["+ i + "]", lectureLoc[i]);
		            	data.intent3.putExtra("lectureNum["+ i + "]", lectureNum[i]);
		        	}
		        	data.intent3.putExtra("column", column);
		        	data.intent3.putExtra("row", row);
		        	data.intent3.putExtra("lecSum[0]", lecSum[0]);
		        	data.intent3.putExtra("lecSum[1]", lecSum[1]);
		        	data.intent3.putExtra("lecSum[2]", lecSum[2]);
		        	int stuIdChk = 0;
		        	try {
		    			FileInputStream fis = openFileInput("stu_id.txt");
		    			BufferedInputStream bis = new BufferedInputStream(fis);
		    			BufferedReader br = new BufferedReader(new InputStreamReader(bis));
		    			//If student are admitted before 2009-year, then use old building name, else use new building name
		    			stuIdChk = Integer.parseInt(br.readLine()) < 2009000000 ? 1 : 0; 
		    			
		    		} catch(Exception e) { e.printStackTrace(); }
		        	data.intent3.putExtra("stuIdChk", stuIdChk);
		        	startActivity(data.intent3);
				}
			});
			
			return layout;
		}

		private class Data {
			public String title1;
			public Bitmap imageFilename1;
			public Intent intent1;
			public String title2;
			public Bitmap imageFilename2;
			public Intent intent2;
			public String title3;
			public Bitmap imageFilename3;
			public Intent intent3;

			private Data(String title1, Bitmap imageFilename1, Intent intent1, String title2, Bitmap imageFilename2, Intent intent2, String title3, Bitmap imageFilename3, Intent intent3) {
				this.title1 = title1;
				this.imageFilename1 = imageFilename1;
				this.intent1 = intent1;
				this.title2 = title2;
				this.imageFilename2 = imageFilename2;
				this.intent2 = intent2;
				this.title3 = title3;
				this.imageFilename3 = imageFilename3;
				this.intent3 = intent3;
			}
		}
	}
    
    //Tap  screen twice in 2 seconds, exit this application.
	private boolean mFlag = false;
	private Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			if(msg.what == 0) mFlag = false;
		}
	};
    @Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
    	if(keyCode == KeyEvent.KEYCODE_BACK) {
    		if(!mFlag) {
    			Toast.makeText(MainMenu.this, "'뒤로' 버튼을 한 번 더 누르시면 종료됩니다.", Toast.LENGTH_SHORT).show();
    			mFlag = true;
    			mHandler.sendEmptyMessageDelayed(0, 2000);
    			return false;
    		} else finish();
    	}
    	return super.onKeyDown(keyCode, event);
    }
}